<template>
  <d2-container>
    <el-card shadow="never" class="tb">
      <div>
        <h2 class="text_center">企业经营监控</h2>
        <p class="text_center">{{ Mydate }}</p>
      </div>
      <el-row :gutter="20">
        <el-col :span="8">
          <h5 class="fl" style="font-size:14px;margin-top:0px">月度销量图</h5>
          <el-select
            class="fr"
            v-model="value_chart"
            size="mini"
            @change="chart_change()"
            placeholder="请选择"
            style="margin-left: 35px;"
          >
            <el-option
              v-for="item in options_chart"
              :key="item.value"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <div
            style="clear:both;border:1px solid #ddd;box-shadow:0 0 5px 0 hsl(0deg 0% 0% / 30%);"
          >
            <div id="main_left" style="width: 100%;height:460px;"></div>
          </div>

          <h5
            class="fl"
            style="font-size:14px;text-align:center;margin-top:0px;margin-top:20px;"
          >
            月度库存图
          </h5>
          <el-select
            class="fr"
            v-model="value_chart_two"
            size="mini"
            @change="chart_change_two()"
            placeholder="请选择"
            style="margin-left: 35px;margin-top:20px;"
          >
            <el-option
              v-for="item in options_chart"
              :key="item.value"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <div
            style="clear:both;margin-top:20px;border:1px solid #ddd;box-shadow:0 0 5px 0 hsl(0deg 0% 0% / 30%);"
          >
            <div id="main_left_center" style="width: 100%;height:460px;"></div>
          </div>
          <h5
            class="fl"
            style="font-size:14px;text-align:center;margin-top:0px;margin-top:20px;"
          >
            销售匹配分析
          </h5>
          <div
            style="clear:both;margin-top:20px;border:1px solid #ddd;box-shadow:0 0 5px 0 hsl(0deg 0% 0% / 30%);"
          >
            <div id="main_left_bottom" style="width: 100%;height:480px;"></div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="center_top">
            <div v-for="(item, indexs) in todayType" :key="indexs">
              <h4 style="color: rgb(255,162,115);">
                今日销售{{ item.name }}数量
              </h4>
              <h3 style="color: rgb(0,204,163);">{{ item.data.diff }}</h3>
            </div>
          </div>
          <h5 class="text_center">策略套保比例监控</h5>
          <div style="height:810px;overflow:auto">
            <div
              style="width:100%;display: flex;"
              v-for="(item, index) in tabedata"
              :key="index"
            >
              <canvas
                :id="'canvas' + index"
                style="margin: 0px auto;"
                width="400"
                height="260"
              ></canvas>
            </div>
          </div>
          <h5 class="text_center" style="margin-top:75px">净敞口日明细表</h5>
          <el-table
            :data="tableData"
            style="width: 100%;"
            height="480"
            class="gd"
            ref="singleTable"
            :cell-style="{
              'text-align': 'center',
              background: '#fff',
              color: '#000'
            }"
            :header-cell-style="{
              'text-align': 'center',
              width: '100%',
              padding: '6px',
              background: '#eef1f6',
              color: '#909399'
            }"
          >
            <el-table-column
              v-for="(item, index) in todatDetails"
              :key="index"
              :prop="item.two"
              :label="item.one"
            >
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="8">
          <h5
            class="fl"
            style="font-size:14px;text-align:center;margin-top:0px;"
          >
            策略盈亏分析
          </h5>
          <div
            style="clear:both;margin-top:20px;border:1px solid #ddd;box-shadow:0 0 5px 0 hsl(0deg 0% 0% / 30%);"
          >
            <div id="main_right" style="width: 100%;height:460px;"></div>
          </div>
          <h5
            class="fl"
            style="font-size:14px;text-align:center;margin-top:0px;margin-top:20px;"
          >
            策略资金占用
          </h5>
          <div
            style="clear:both;margin-top:20px;border:1px solid #ddd;box-shadow:0 0 5px 0 hsl(0deg 0% 0% / 30%);"
          >
            <div id="main_right_center" style="width: 100%;height:460px;"></div>
          </div>
          <h5
            class="fl"
            style="font-size:14px;text-align:center;margin-top:0px;margin-top:20px;"
          >
            未定价敞口趋势
          </h5>
          <el-select
            class="fr"
            v-model="value_open"
            size="mini"
            @change="chart_open()"
            placeholder="请选择"
            style="margin-left: 35px;margin-top:20px;"
          >
            <el-option label="采购 " value="0"></el-option>
            <el-option label="销售" value="1"></el-option>
          </el-select>
          <div
            style="clear:both;margin-top:20px;border:1px solid #ddd;box-shadow:0 0 5px 0 hsl(0deg 0% 0% / 30%);"
          >
            <div id="main_right_bottom" style="width: 100%;height:480px;"></div>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </d2-container>
</template>
<script>
import dayjs from "dayjs";
import {
  getReport_hedging_ratio,
  getReport_profit_loss,
  getReport_strategy_caps,
  getReport_product_position
} from "@/api/url";
export default {
  data() {
    return {
      Mydate: dayjs().format("YYYY-MM-DD HH:mm:ss"),
      timeInterval: null,
      tableData: [],
      ctx: "",
      circleX: "",
      circleY: "",
      ctx_center: "",
      circleX_center: "",
      circleY_center: "",
      ctx_bottom: "",
      circleX_bottom: "",
      circleY_bottom: "",
      angle: 0,
      // 今日销售的
      todayType: [],
      // 净敞口日明细表
      todatDetails: [],
      // 仪表盘图
      tabedata: [],
      value_chart: 2021,
      value_chart_two: 2021,
      value_open: "0",
      options_chart: [
        {
          value: 2020
        },
        {
          value: 2021
        },
        {
          value: 2022
        }
      ]
    };
  },
  beforeDestroy() {
    clearInterval(this.timeInterval);
  },
  created() {
    let toplist = {
      type: "sales_volume"
    };
    getReport_product_position(toplist).then(res => {
      this.todayType = res.result;
    });
    // 净敞口 表
    let listss = {
      type: "exp_trend"
    };
    getReport_product_position(listss).then(res => {
      this.tableData = res.result;
      let arr = [];
      let obj = res.result[0];
      for (let i in obj) {
        let o = {};
        o["one"] = i;
        o["two"] = i;
        arr.push(o);
      }
      arr[1].one = "方向";
      arr[0].one = "时间";
      this.todatDetails = arr;
    });
  },
  methods: {
    chart_change() {
      this.chart_onefn();
    },
    chart_onefn() {
      // 第1个
      let datas1 = {
        type: "monthly_sales",
        year: this.value_chart
      };
      getReport_product_position(datas1).then(res => {
        let namelist = [];
        let datass = [];
        res.result.forEach(item => {
          namelist.push(item.name);
          var arrys = {
            name: item.name,
            type: "bar",
            data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
          };
          item.data.forEach(inss => {
            var indexs = inss.month * 1 - 1;
            arrys.data[indexs] = inss.diff;
          });
          datass.push(arrys);
        });
        console.log(namelist, datass);
        this.$nextTick(() => {
          this.drawChart1(namelist, datass);
        });
      });
    },
    chart_change_two() {
      this.chart_twofn();
    },

    chart_twofn() {
      let datas2 = {
        type: "monthly_inventory",
        year: this.value_chart_two
      };
      getReport_product_position(datas2).then(res => {
        let namelist = [];
        let datass = [];
        res.result.forEach(item => {
          namelist.push(item.name);
          var arrys = {
            name: item.name,
            type: "bar",
            data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
          };
          item.data.forEach(inss => {
            var indexs = inss.month * 1 - 1;
            arrys.data[indexs] = inss.diff;
          });
          datass.push(arrys);
        });
        this.$nextTick(() => {
          this.drawChart2(namelist, datass);
        });
      });
    },
    chart_open() {
      let datas9 = {
        type: "net_exp_trend",
        direction: this.value_open
      };
      getReport_product_position(datas9).then(res => {
        let titleData = [];
        let times = [];
        let datass = [];
        res.result[0].data.forEach(items => {
          times.push(items.date);
        });
        res.result.forEach(item => {
          titleData.push(item.name);
          let a = {
            name: item.name,
            type: "line",
            data: []
          };
          item.data.forEach(ins => {
            a.data.push(ins.diff);
          });
          datass.push(a);
        });
        this.$nextTick(() => {
          this.drawChart9(titleData, times, datass);
        });
      });
    },

    refreshTime() {
      this.Mydate = dayjs().format("YYYY-MM-DD HH:mm:ss");
    },
    drawChart1(xdata, ydata) {
      // 基于准备好的dom，初始化echarts实例
      let myChart_left = this.$echarts.init(
        document.getElementById("main_left")
      );
      myChart_left.setOption({
        // title: {
        //   text: "月度销量图",
        //   left: "center"
        // },
        color: ["#27c09c", "#e65952", "#e89533", "#e5323e"],
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow"
          }
        },
        legend: {
          data: xdata,
          bottom: 10,
          left: "center",
          textStyle: {
            color: "#000"
          }
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: [
          {
            type: "category",
            axisTick: {
              show: false
            },
            data: [
              "1",
              "2",
              "3",
              "4",
              "5",
              "6",
              "7",
              "8",
              "9",
              "10",
              "11",
              "12"
            ]
          }
        ],
        yAxis: [
          {
            type: "value"
          }
        ],
        series: ydata
      });
    },
    drawChart2(xdata, ydata) {
      let myChart_left_center = this.$echarts.init(
        document.getElementById("main_left_center")
      );
      myChart_left_center.setOption({
        // title: {
        //   text: "月度库存图",
        //   left: "center"
        // },
        color: ["#27c09c", "#e65952", "#e89533", "#e5323e"],
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow"
          }
        },
        legend: {
          data: xdata,
          bottom: 10,
          left: "center"
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: [
          {
            type: "category",
            axisTick: {
              show: false
            },
            data: [
              "1",
              "2",
              "3",
              "4",
              "5",
              "6",
              "7",
              "8",
              "9",
              "10",
              "11",
              "12"
            ]
          }
        ],
        yAxis: [
          {
            type: "value"
          }
        ],
        series: ydata
      });
    },
    drawChart3(xdata, ydata) {
      let myChart_left_bottom = this.$echarts.init(
        document.getElementById("main_left_bottom")
      );
      myChart_left_bottom.setOption({
        title: {
          // text: "匹配分析",
          left: "center"
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow" // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        color: ["#e65952"],
        legend: {
          data: ["matched", "unmatched"],
          bottom: 0,
          left: "center"
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "8%",
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: [
          {
            type: "category",
            data: xdata
          }
        ],
        yAxis: [
          {
            type: "value"
          }
        ],
        series: ydata
      });
    },
    drawChart7(xdata, ydata) {
      let myChart_right = this.$echarts.init(
        document.getElementById("main_right")
      );
      myChart_right.setOption({
        title: {
          // text: "策略盈亏分析",
          left: "center"
        },
        color: ["#e65952"],
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow" // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: [
          {
            type: "value"
          }
        ],
        yAxis: [
          {
            type: "category",
            axisTick: {
              show: false
            },
            data: ydata
          }
        ],
        series: [
          {
            name: "利润",
            type: "bar",
            label: {
              show: true,
              position: "inside"
            },
            data: xdata
          }
        ]
      });
    },
    drawChart8(xdata, ydata) {
      let myChart_right_center = this.$echarts.init(
        document.getElementById("main_right_center")
      );
      myChart_right_center.setOption({
        title: {
          // text: "策略资金占用",
          left: "center"
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        color: [
          "#27c09c",
          "#1E90FF",
          "#e65952",
          "#e89533",
          "#a370d4",
          "#80c250"
        ],
        legend: {
          // orient: 'vertical',
          // top: 'middle',
          bottom: 10,
          left: "center",
          data: ydata
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        series: [
          {
            name: "策略资金占用",
            type: "pie",
            radius: "65%",
            center: ["50%", "50%"],
            selectedMode: "single",
            data: xdata,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)"
              }
            }
          }
        ]
      });
    },
    drawChart9(dataone, datatwo, datathree) {
      let myChart_right_bottom = this.$echarts.init(
        document.getElementById("main_right_bottom")
      );
      myChart_right_bottom.setOption({
        title: {
          // text: "未定价敞口趋势",
          left: "center"
        },
        color: ["#27c09c", "#e65952", "#e89533"],
        tooltip: {
          trigger: "axis"
        },
        legend: {
          data: dataone,
          bottom: 0,
          left: "center"
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "15%",
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: datatwo
        },
        yAxis: {
          type: "value"
        },
        series: datathree
      });
    },

    // 仪表盘图
    canvas_fns(index) {
      let canvas = document.getElementById("canvas" + index);
      this.tabedata[index].ctx = canvas.getContext("2d");
      this.tabedata[index].circleX = canvas.width / 2; // 中心x坐标
      this.tabedata[index].circleY = 150; //中心y坐标
    },
    circles(r, w, c, angle = 180, index) {
      let ctx = this.tabedata[index].ctx;
      // 画布将当前的状态保存
      // canvas.save();与canvas.restore();一般结合使用，.save()函数在前，.restore()函数在后，
      // 用来保证在这两个函数之间所做的操作不会对原来在canvas上所画图形产生影响
      ctx.save();
      // 开始一条路径，或重置当前的路径
      ctx.beginPath();
      // 设置线条的宽度
      ctx.lineWidth = w;
      // 设置线条的颜色
      ctx.strokeStyle = c;
      // 线条末端线帽的设置为圆形
      ctx.lineCap = "round";
      // 方法创建弧/曲线（用于创建圆或部分圆）
      ctx.arc(
        this.tabedata[index].circleX,
        this.tabedata[index].circleY,
        r,
        Math.PI,
        Math.PI * (1 + angle / 180)
      );
      ctx.stroke();
      // 画布取出原来所保存的状态
      ctx.restore();
    },
    scales(s, span, sl, el, c, index) {
      let ctx = this.tabedata[index].ctx;
      let startA = s;
      for (let i = 0; i < span; i++) {
        ctx.save();
        ctx.beginPath();
        let rad = (startA * 15 * Math.PI) / 180;
        let startX = 200 - Math.cos(rad) * sl;
        let startY = 150 - Math.sin(rad) * sl;
        let endX = 200 - Math.cos(rad) * el;
        let endY = 150 - Math.sin(rad) * el;
        // 路径移动到画布中的指定点，不创建线条
        ctx.moveTo(startX, startY);
        // 添加一个新点，然后创建从该点到画布中最后指定点的线条（该方法并不会创建线条）
        ctx.lineTo(endX, endY);
        ctx.strokeStyle = c;
        // 方法会实际地绘制出通过 moveTo() 和 lineTo() 方法定义的路径。默认颜色是黑色。
        ctx.stroke();
        ctx.restore();
        startA++;
      }
    },
    fillTexts(text, x, y, color = "#333", fontSize = "18", index) {
      let ctx = this.tabedata[index].ctx;
      ctx.save();
      // 根据锚点，设置或返回文本内容的当前对齐方式    水平方向
      ctx.textAlign = "center";
      // 设置或返回在绘制文本时的当前文本基线    垂直方向
      ctx.textBaseline = "middle";
      // 设置或返回画布上文本内容的当前字体属性
      ctx.font = fontSize + "px Arial";
      ctx.fillStyle = color;
      // 在画布上绘制填色的文本
      ctx.fillText(text, x, y);
      ctx.restore();
    },
    rounds(x, y, r, fillColor = "#fff", lineWidth = 3, index) {
      let ctx = this.tabedata[index].ctx;
      ctx.save();
      ctx.beginPath();
      ctx.lineWidth = lineWidth;
      ctx.strokeStyle = "#7775FD";
      ctx.arc(x, y, r, 0, Math.PI * 2, false);
      ctx.fillStyle = fillColor;
      // 填充当前的图像（路径）。默认颜色是黑色
      ctx.fill();
      ctx.stroke();
      ctx.restore();
    },
    triangles(angle, index) {
      let ctx = this.tabedata[index].ctx;
      ctx.save();
      ctx.beginPath();
      ctx.lineWidth = 1;
      let rad = (angle * Math.PI) / 180;
      let startX = this.tabedata[index].circleX - Math.cos(rad) * 40;
      let startY = this.tabedata[index].circleY - Math.sin(rad) * 40;
      ctx.moveTo(startX, startY);
      let rad1 = ((90 - angle) * Math.PI) / 180;
      let startX1 = this.tabedata[index].circleX - Math.cos(rad1) * 11;
      let startY1 = this.tabedata[index].circleY + Math.sin(rad1) * 11;
      ctx.lineTo(startX1, startY1);
      let rad2 = ((90 - angle) * Math.PI) / 180;
      let startX2 = this.tabedata[index].circleX + Math.cos(rad2) * 11;
      let startY2 = this.tabedata[index].circleY - Math.sin(rad2) * 11;
      ctx.lineTo(startX2, startY2);
      ctx.closePath();
      ctx.fillStyle = "#8382FF";
      ctx.fill();
      ctx.strokeStyle = "#8382FF";
      ctx.stroke();
      ctx.restore();
    },
    draws(angle, name, bai, index) {
      this.tabedata[index].ctx.clearRect(
        0,
        0,
        this.tabedata[index].circleX * 2,
        this.tabedata[index].circleY * 2
      );
      this.circles(96, 8, "#F8F8F8", 180, index);
      this.circles(80, 2, "#BBBAFF", 180, index);
      this.circles(64, 12, "#F2F2F2", 180, index);
      this.circles(40, 2, "#F8F8F8", 180, index);
      this.circles(24, 2, "#F8F8F8", 180, index);
      this.scales(0, 13, 65, 62, "#F2F2F2", index);
      this.scales(0.5, 12, 65, 58, "#F2F2F2", index);
      this.fillTexts("低", 100, 100, "#333", "18", index);
      this.fillTexts("中", 165, 40, "#333", "18", index);
      this.fillTexts("高", 235, 40, "#333", "18", index);
      this.fillTexts("预警", 300, 80, "#333", "18", index);
      this.fillTexts("警告", 320, 120, "#333", "18", index);
      this.fillTexts(name, 200, 210, "#9A9A9A", "16", index);
      this.fillTexts(bai, 200, 230, "#62C513", "12", index);
      this.rounds(120, 150, 4, "#fff", 3, index);
      this.rounds(150, 88, 4, "#fff", 3, index);
      this.rounds(200, 70, 4, "#fff", 3, index);
      this.rounds(250, 88, 4, "#fff", 3, index);
      this.rounds(266, 105, 4, "#fff", 3, index);
      this.rounds(280, 150, 4, "#fff", 3, index);
      this.rounds(200, 150, 10, "#8382FF", 1, index);
      if (angle > 0) {
        this.circles(64, 12, "#7775FD", angle, index); //这里换选中的颜色
      }
      this.triangles(angle, index);
      this.rounds(200, 150, 4, "#fff", 3, index);
    }
  },
  mounted() {
    // 第1个
    this.chart_onefn();
    // 第2个
    this.chart_twofn();
    // 第3个
    this.chart_open();
    let datas3 = {
      type: "matching_analysis",
      year: "2020"
    };
    getReport_product_position(datas3).then(res => {
      let nameData = [];
      let datassss = [
        {
          name: "已匹配",
          type: "bar",
          stack: "广告",
          data: []
        },
        {
          name: "未匹配",
          type: "bar",
          stack: "广告",
          data: []
        }
      ];
      res.result.forEach(item => {
        nameData.push(item.name);
        datassss[0].data.push(item.match_amount);
        datassss[1].data.push(item.diff);
      });
      this.$nextTick(() => {
        this.drawChart3(nameData, datassss);
      });
    });
    //第7个 策略盈亏分析
    let datas7 = {
      request_type: "comprehensive"
    };
    getReport_profit_loss(datas7).then(res => {
      let Xdata = [];
      let Ydata = [];
      res.result.forEach(item => {
        Xdata.push(item.diffAll);
        Ydata.push(item.strategy_name + item.strategy_id);
      });
      this.$nextTick(() => {
        this.drawChart7(Xdata, Ydata);
      });
    });
    //第8个 策略资金占用
    let datas8 = {
      data_type: "comprehensive"
    };
    getReport_strategy_caps(datas8).then(res => {
      let Ydata = [];
      res.result.forEach(item => {
        Ydata.push(item.strategy_name);
        item.value = item.total;
        item.name = item.strategy_name + item.strategy_id;
      });
      let Xdata = res.result;
      this.$nextTick(() => {
        this.drawChart8(Xdata, Ydata);
      });
    });
    //最后一个 未定价敞口趋势

    //中间3个
    let datas333 = {
      type: "comprehensive"
    };
    getReport_hedging_ratio(datas333).then(res => {
      let datasssss = [];
      res.result.forEach(item => {
        let aaa = {
          ctx: "",
          circleX: "",
          circleY: "",
          name: "",
          nums: "",
          bai: ""
        };
        aaa.name = item.strategy_name + item.strategy_id;
        if (item.actual_hr === "-" || item.actual_hr === "0.0000") {
          aaa.nums = 0;
          aaa.bai = "0%";
        } else {
          aaa.nums = item.actual_hr * 1 * 180;
          let datal = item.actual_hr * 100;
          aaa.bai = datal.toFixed(2) + "%";
        }
        datasssss.push(aaa);
      });
      this.tabedata = datasssss;
      this.$nextTick(() => {
        for (let i = 0; i < this.tabedata.length; i++) {
          this.canvas_fns(i);
          this.draws(
            this.tabedata[i].nums,
            this.tabedata[i].name,
            this.tabedata[i].bai,
            i
          );
        }
      });
    });
    // 实时时间
    this.timeInterval = setInterval(() => {
      this.refreshTime();
    }, 1000);
  }
};
</script>
<style scoped>
.el-table th,
.el-table tr {
  background-color: #eef1f6;
}
.gd .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background: #1e90ff;
  border-radius: 2px;
}
.gd .el-table__body-wrapper::-webkit-scrollbar-track {
  background: #eef1f6;
}
.text_center {
  text-align: center;
}

.center_top {
  display: flex;
  justify-content: space-around;
  text-align: center;
}

.tb ::-webkit-scrollbar {
  width: 8px;
}

.tb ::-webkit-scrollbar-thumb {
  background-color: #eaecf1;
  border-radius: 3px;
}
</style>
